import router from "@/router"
import NProgress from "nprogress"
import "nprogress/nprogress.css"
import { getToken } from "./utils/auth"
import { useUserStore } from "./stores/user"
import { usePermissionStore } from "./stores/permission"

NProgress.configure({ showSpinner: false })
const whiteList = ["/login"] // ⽩名单
router.beforeEach(async (to) => {
  NProgress.start()
  const hasToken = getToken()
  const userStore = useUserStore()
  const permissionStore = usePermissionStore()

  if (hasToken) {
    // 有token代表已登录
    if (to.path === "/login") {
      NProgress.done()
      return {
        path: "/",
        replace: true //替换当前的历史记录，即后退不会返回到登录页
      }
    } else {
      // 登录后获取 用户信息， 也有可能token是伪造的
      try {
        const hasRoles = userStore.state.roles.length > 0
        if (hasRoles) {
          NProgress.done()
          return true
        }
        await userStore.getUserInfo()
        // const roles = userStore.state.roles // 稍后用角色来生成菜单树
        const routes = await permissionStore.generateRoutes()
        routes.forEach(router.addRoute) // 内部添加到映射表中,将每个元素作为参数传递给 router.addRoute ，并执行
        return router.push(to.path) //添加之后需再次跳路径
      } catch {
        userStore.logout()
        NProgress.done()
        return "/login?redirect=" + to.path
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      NProgress.done()
      return true
    }
    NProgress.done()

    return {
      path: "/login",
      query: {
        redirect: to.path, //登录成功后能够返回到原本想要访问的页面。
        ...to.query
      }
    }
  }
})
router.afterEach(() => {
  NProgress.done()
})
